import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElSelect,
  ElOption,
  ElIcon,
  ElTimeSelect,
  ElDatePicker,
  ElRow,
  ElCol
} from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'
import type { InfoValuesType, nodeType, optionsType, groupType } from './typings'
import { Plus, CloseBold } from '@element-plus/icons-vue'
import { GUTTER } from '~/utils/const'
import styles from '../../index.module.scss'
import { handleTrim } from '~/utils/util'

import InputTextarea from '~/components/ProForm/InputTextarea'

export default defineComponent({
  props: ['cancel', 'type', 'visible', 'record', 'groupList'],
  emits: ['submitForm'],
  setup(props, { emit }) {
    const store = useStore()
    const infoTrans = (data: string) => {
      const res = data.split('|')
      const arr: any = []
      res.forEach((item) => {
        const regex1 = /(\S*)\(/
        const regex2 = /\((\S*)\)/
        const time = item.match(regex1)
        const content = item.match(regex2)
        arr.push({
          nodeTime: time![1],
          nodeParam: content![1]
        })
      })
      arr.forEach((item: nodeType) => {
        const _item = item.nodeParam?.split(',')
        item.dimmer1 = _item[0]
        item.dimmer2 = _item[1]
        item.dimmer3 = _item[2]
        item.dimmer4 = _item[3]
      })
      return arr
    }
    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive<InfoValuesType>(
      Object.assign(
        {},
        props?.record?.id // 初始化数据
          ? {
              id: props.record.id,
              taskName: props.record.taskName,
              memo: props.record.memo,
              groupIdArr: props.record.groupIds.split(','),
              nodeList: infoTrans(props.record.info),
              dateRange: [props.record.startDate, props.record.endDate]
            }
          : {
              nodeList: [
                {
                  nodeCode: 0,
                  nodeTime: '',
                  nodeParam: ''
                },
                {
                  nodeCode: 0,
                  nodeTime: '',
                  nodeParam: ''
                }
              ]
            }
      )
    )
    const state = reactive({
      options: [
        { value: '0', key: '0' },
        { value: '10', key: '10' },
        { value: '20', key: '20' },
        { value: '30', key: '30' },
        { value: '40', key: '40' },
        { value: '50', key: '50' },
        { value: '60', key: '60' },
        { value: '70', key: '70' },
        { value: '80', key: '80' },
        { value: '90', key: '90' },
        { value: '100', key: '100' }
      ],
      groupList: []
    })

    const rules = reactive<FormRules>({
      taskName: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }],
      dateRange: [
        {
          type: 'array',
          required: true,
          message: '请选择自动下发配置的有效时间范围',
          fields: {
            // tpye类型试情况而定,所以如果返回的是date就改成date
            0: { type: 'string', required: true, message: '请选择开始日期' },
            1: { type: 'string', required: true, message: '请选择结束日期' }
          }
        }
      ],
      groupIds: [{ required: true, message: '请选择分组', trigger: 'blur' }],
      dimmer1: [{ required: true, message: '请选择回路1调光比例', trigger: 'change' }],
      dimmer2: [{ required: true, message: '请选择回路2调光比例', trigger: 'change' }],
      dimmer3: [{ required: true, message: '请选择回路3调光比例', trigger: 'change' }],
      dimmer4: [{ required: true, message: '请选择回路4调光比例', trigger: 'change' }],
      nodeTime: [
        { required: true, message: '请选择调光时间', trigger: 'change' },
        {
          required: true,
          validator: (rule, value, callback) => {
            if (rule.field === 'nodeList.1.nodeTime') {
              const num0 = numnerTime(ruleForm.nodeList![0].nodeTime!)
              const num1 = numnerTime(value)
              // 先判断当前的时间处于哪一个时间段  17 - 23 还是 00 - 8  还是 8-17
              if (num1 >= 1700 && num1 <= 2300) {
                // 如果前一个时间是下午的时间  则第二个时间要大于第一个
                if (num0 >= 1700 && num0 <= 2300) {
                  if (num1 <= num0) {
                    callback(new Error('必须大于一级调光时间'))
                  } else {
                    callback()
                  }
                } else if (num0 >= 0 && num0 <= 800) {
                  callback(new Error('请选择 00:00至8:00'))
                }
              } else if (num1 >= 0 && num1 <= 800) {
                if (num0 >= 0 && num0 <= 800) {
                  if (num1 <= num0) {
                    callback(new Error('必须大于一级调光时间'))
                  } else {
                    callback()
                  }
                } else if (num0 >= 1700 && num0 <= 2300) {
                  callback()
                }
              } else {
                callback(new Error('调光时间17:00至8:00'))
              }
            } else if (rule.field === 'nodeList.2.nodeTime') {
              const num0 = numnerTime(ruleForm?.nodeList![1].nodeTime!)
              const num1 = numnerTime(value)

              // 先判断当前的时间处于哪一个时间段  17 - 23 还是 00 - 8  还是 8-17
              if (num1 >= 1700 && num1 <= 2300) {
                // 如果前一个时间是下午的时间  则第二个时间要大于第一个
                if (num0 >= 1700 && num0 <= 2300) {
                  if (num1 <= num0) {
                    callback(new Error('必须大于二级调光时间'))
                  } else {
                    callback()
                  }
                } else if (num0 >= 0 && num0 <= 800) {
                  callback(new Error('请选择 00:00至8:00'))
                }
              } else if (num1 >= 0 && num1 <= 800) {
                if (num0 >= 0 && num0 <= 800) {
                  if (num1 <= num0) {
                    callback(new Error('必须大于二级调光时间'))
                  } else {
                    callback()
                  }
                } else if (num0 >= 1700 && num0 <= 2300) {
                  callback()
                }
              } else {
                callback(new Error('调光时间17:00至8:00'))
              }
            } else if (rule.field === 'nodeList.3.nodeTime') {
              const num0 = numnerTime(ruleForm?.nodeList![2].nodeTime!)
              const num1 = numnerTime(value)
              // 先判断当前的时间处于哪一个时间段  17 - 23 还是 00 - 8  还是 8-17
              if (num1 >= 1700 && num1 <= 2300) {
                // 如果前一个时间是下午的时间  则第二个时间要大于第一个
                if (num0 >= 1700 && num0 <= 2300) {
                  if (num1 <= num0) {
                    callback(new Error('必须大于三级调光时间'))
                  } else {
                    callback()
                  }
                } else if (num0 >= 0 && num0 <= 800) {
                  callback(new Error('请选择 00:00至8:00'))
                }
              } else if (num1 >= 0 && num1 <= 800) {
                if (num0 >= 0 && num0 <= 800) {
                  if (num1 <= num0) {
                    callback(new Error('必须大于三级调光时间'))
                  } else {
                    callback()
                  }
                } else if (num0 >= 1700 && num0 <= 2300) {
                  callback()
                }
              } else {
                callback(new Error('调光时间17:00至8:00'))
              }
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ]
    })
    const numnerTime = (value: string) => {
      return Number(value.replace(/:/, ''))
    }

    // 新增调光参数
    const addDimming = () => {
      ruleForm.nodeList!.push({
        nodeCode: 0,
        nodeTime: '',
        nodeParam: ''
      })
    }
    // 删除调光参数
    const delDimming = (index: number) => {
      ruleForm.nodeList!.splice(index, 1)
    }
    //  提交
    const submitForm = () => {
      ruleFormRef.value?.validate(async (valid) => {
        if (valid) {
          const params = { ...ruleForm }
          params.taskName = handleTrim(params.taskName!)
          params.startDate = params.dateRange?.[0]
          params.endDate = params.dateRange?.[1]
          params.groupIds = params.groupIdArr?.join(',')
          const str = params.nodeList?.map(
            (item) =>
              `${item.nodeTime}(${item.dimmer1},${item.dimmer2},${item.dimmer3},${item.dimmer4})`
          )
          params.info = str?.join('|')
          delete params.groupIdArr
          delete params.dateRange
          delete params.nodeList

          if (props.type === 'update') params.id = props.record?.id
          const { code } = await store.dispatch(
            props.type === 'add' ? 'singleLamp/TaskAdd' : 'singleLamp/TaskUpdate',
            params
          )
          if (code === 200) {
            ElMessage({
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            emit('submitForm')
            props.cancel()
          }
        }
      })
    }
    //  取消
    const resetForm = () => {
      ruleFormRef.value?.resetFields()
      props.cancel()
    }
    onMounted(async () => {
      // 分组数据
      const { data } = await store.dispatch('singleLamp/GroupData')
      state.groupList = data
    })
    return () => (
      <ElDialog
        title={props.type === 'add' ? '新增策略' : '编辑策略'}
        modelValue={props.visible}
        beforeClose={props.cancel}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        width={1360}
        v-slots={{
          footer: () => (
            <>
              <ElButton onClick={resetForm}>取消</ElButton>
              <ElButton type="primary" onClick={submitForm}>
                确定
              </ElButton>
            </>
          )
        }}
      >
        <ElForm
          ref={ruleFormRef}
          model={ruleForm}
          rules={rules}
          label-width="130px"
          labelPosition="right"
        >
          <ElRow gutter={GUTTER}>
            <ElCol span={7}>
              <ElFormItem label="策略名称" prop="taskName">
                <ElInput
                  v-model={ruleForm.taskName}
                  class={styles['model-input']}
                  placeholder="请输入策略名称"
                ></ElInput>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow gutter={GUTTER}>
            <ElCol span={7}>
              <ElFormItem label="策略内容" prop="dateRange">
                <ElDatePicker
                  v-model={ruleForm.dateRange}
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  valueFormat="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  type="daterange"
                  clearable
                  style="margin-bottom:16px"
                />
                <div class={styles['equipment-box']}>
                  {ruleForm.nodeList!?.map((item: nodeType, index) => (
                    <div class={styles['equipment-box-style']}>
                      {ruleForm.nodeList!.length > 1 && (
                        <i class={styles.positionIcon} onClick={() => delDimming(index)}>
                          <ElIcon>
                            <CloseBold />
                          </ElIcon>
                        </i>
                      )}
                      <div class={styles['box-style-title']}>{index + 1}级调光</div>
                      <ElFormItem
                        label="时间"
                        prop={`nodeList.${  index  }.nodeTime`}
                        rules={rules.nodeTime}
                        label-width="120px"
                        style="margin: 0 10px 16px 0;"
                      >
                        <ElTimeSelect
                          v-model={item.nodeTime}
                          placeholder="选择时间"
                          start="00:00"
                          step="01:00"
                          end="23:00"
                        ></ElTimeSelect>
                      </ElFormItem>
                      <ElFormItem
                        label="回路1调光比例"
                        prop={`nodeList.${  index  }.dimmer1`}
                        rules={rules.dimmer1}
                        label-width="120px"
                        style="margin: 0 10px 16px 0;"
                      >
                        <ElSelect v-model={item.dimmer1} clearable placeholder="回路1调光比例">
                          {state.options?.map((el: optionsType) => (
                            <ElOption key={el?.key} label={el?.value} value={el.key} />
                          ))}
                        </ElSelect>
                      </ElFormItem>
                      <ElFormItem
                        label="回路2调光比例"
                        prop={`nodeList.${  index  }.dimmer2`}
                        rules={rules.dimmer2}
                        label-width="120px"
                        style="margin: 0 10px 16px 0;"
                      >
                        <ElSelect v-model={item.dimmer2} clearable placeholder="回路2调光比例">
                          {state.options?.map((el: optionsType) => (
                            <ElOption key={el?.key} label={el?.value} value={el.key} />
                          ))}
                        </ElSelect>
                      </ElFormItem>
                      <ElFormItem
                        label="回路3调光比例"
                        prop={`nodeList.${  index  }.dimmer3`}
                        rules={rules.dimmer3}
                        label-width="120px"
                        style="margin: 0 10px 16px 0;"
                      >
                        <ElSelect v-model={item.dimmer3} clearable placeholder="回路3调光比例">
                          {state.options?.map((el: optionsType) => (
                            <ElOption key={el?.key} label={el?.value} value={el.key} />
                          ))}
                        </ElSelect>
                      </ElFormItem>
                      <ElFormItem
                        label="回路4调光比例"
                        prop={`nodeList.${  index  }.dimmer4`}
                        rules={rules.dimmer4}
                        label-width="120px"
                        style="margin: 0 10px 16px 0;"
                      >
                        <ElSelect v-model={item.dimmer4} clearable placeholder="回路4调光比例">
                          {state.options?.map((el: optionsType) => (
                            <ElOption key={el?.key} label={el?.value} value={el.key} />
                          ))}
                        </ElSelect>
                      </ElFormItem>
                    </div>
                  ))}
                  {ruleForm.nodeList!.length < 4 && (
                    <div class={styles['flex-col']} onClick={addDimming}>
                      <ElIcon size={40}>
                        <Plus />
                      </ElIcon>
                      <div style="color: #606266;cursor: pointer;">新增调光参数</div>
                    </div>
                  )}
                </div>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow gutter={GUTTER}>
            <ElCol span={7}>
              <ElFormItem label="分组名称" prop="groupIdArr">
                <ElSelect
                  v-model={ruleForm.groupIdArr}
                  clearable
                  placeholder="分组名称"
                  multiple
                  collapse-tags
                  class={styles['model-input']}
                >
                  {state.groupList?.map((item: groupType) => (
                    <ElOption key={item?.id} label={item?.name} value={item?.id} />
                  ))}
                </ElSelect>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow gutter={GUTTER}>
            <ElCol span={10}>
              <ElFormItem label="备注" prop="memo">
                <InputTextarea
                  v-model:inputTextareaValue={ruleForm.memo}
                  placeholderName="请输入内容"
                  limitLength={200}
                />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </ElDialog>
    )
  }
})
